﻿using AutoMapper;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Infratrveture;
using B.S.Filtration.Read.Api.Application.Command.Feeding;
using B.S.Filtration.Read.Api.Dto;
using MediatR;

namespace B.S.Filtration.Read.Api.Application.CommandHander.Feeding
{
    public class GetFeedingHander : IRequestHandler<GetFeedingCommand, APIPaging<List<FeedingDto>>>
    {

        private readonly IMapper mapper;
        private readonly DapperContext db;

        public GetFeedingHander(IMapper mapper, DapperContext db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 显示投料信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPaging<List<FeedingDto>>> Handle(GetFeedingCommand request, CancellationToken cancellationToken)
        {
            APIPaging<List<FeedingDto>> paging = new APIPaging<List<FeedingDto>>();

            var offset = (request.PageIndex - 1) * request.PageSize;
            var listQuery = $"SELECT * FROM Feeding ORDER BY FeedingId ASC LIMIT {offset},{request.PageSize}";
            var totalCountQuery = $"SELECT COUNT(*) FROM Feeding";

            paging.TotalCount = await db.QuerySingleAsync<int>(totalCountQuery);

            paging.TotalPage = (int)Math.Ceiling((double)paging.TotalCount / request.PageSize);

            var result = await db.QueryAsync<FeedingDto>(listQuery);

            paging.data = result.ToList();

            return paging;
        }
    }
}
